package atguigu.web;

import atguigu.pojo.User;
import atguigu.service.UserService;
import atguigu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求的参数  前端用户注册输入的参数，用户名和密码
        String username = req.getParameter("username");//与.jsp文件中 input中name属性的值统一
        String password = req.getParameter("password");
        //2.检查验证码是否正确  这里验证码先写死
//        3、检查 用户名是否可用
        if(username==null || password==null ||(password==null&&password==null)){
            System.out.println("用户名或者密码为空!");
//        跳回注册页面
            req.getRequestDispatcher("/regist.jsp").forward(req, resp);
        } else if (userService.existUsername(username)) {
            //保存回显数据到域中 显示错误信息
            req.setAttribute("msg","用户名已经存在");
            req.setAttribute("username",username);
//        跳回注册页面
                req.getRequestDispatcher("/regist.jsp").forward(req, resp);
        }  else {
                //      可用
//                调用Sservice保存到数据库
                userService.registUser(new User(null, username, password));
//
//        跳到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("/pages/succes.jsp").forward(req, resp);
            }


    }
}
